package com.details;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class ImageUtils {
    /**
     *
     * @param x1 背景图左上角坐标x轴
     * @param y1 背景图左上角坐标y轴
     * @param x2 背景图右下角坐标x轴
     * @param y2 背景图右下角坐标y轴
     * @param backgroundPath 背景图路径
     * @param uiPath ui图路径
     * @param logoList 水印list
     * @param outPath 合成图片后输出的路径
     */
    public static void margeImage(int x1, int y1, int x2, int y2, String backgroundPath, String uiPath, ArrayList<Logo> logoList, String outPath) throws IOException {
        System.out.println(backgroundPath+",,,backgroundPath");
        File file = new File(backgroundPath);
        Image img = ImageIO.read(file);
        //背景图宽度
        int width = img.getWidth(null);
        //背景图高度
        int height = img.getHeight(null);
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g.drawImage(img.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        //透明度
        float clarity = 1.0f;
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, clarity));

        //背景图定位的ui宽度
        int uXSize = x2 - x1;
        //背景图定位的ui长度
        int uYSize = y2 - y1;

        //设置ui图相关属性
        ImageIcon uiImgIcon = new ImageIcon(uiPath);
        uiImgIcon.setImage(uiImgIcon.getImage().getScaledInstance(uXSize,uYSize,Image.SCALE_DEFAULT));
        Image uiCon = uiImgIcon.getImage();

        //ui的位置
        g.drawImage(uiCon,x1, y1, null);

        //设置其他图片水印
        for (Logo logo:logoList) {
            //设置其他图相关属性
            ImageIcon otherImgIcon = new ImageIcon(logo.getPath());
            uiImgIcon.setImage(otherImgIcon.getImage().getScaledInstance(logo.getX2()-logo.getX1(),logo.getY2()-logo.getY1(),Image.SCALE_DEFAULT));
            Image otherICon = uiImgIcon.getImage();
            //其他图片的位置
            g.drawImage(otherICon,logo.getX1(), logo.getY1(), null);
        }

        g.dispose();
        File sf = new File(outPath);
        // 保存图片
        ImageIO.write(bi, "png", sf);
    }
}
